package com.zztl.infiniteBand.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleDataCountCallback.BleStepCallback
import com.clj.fastble.utils.BleLog
import com.zztl.infiniteBand.BraceletApplication
import com.zztl.infiniteBand.eventbus.SyncStepCount
import com.zztl.infiniteBand.eventbus.WatchStepEvent
import com.zztl.infiniteBand.model.NoDataResponseBean
import com.zztl.infiniteBand.net.FilterSubscriber2
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.converter.DataConverter
import com.zztl.infiniteBand.net.requestBean.SyncStepRequest
import com.zztl.infiniteBand.util.LogUtils
import org.greenrobot.eventbus.EventBus


/**
 *  @desc
 *  @auth ${user}
 *  @time 2018/10/25  11:13
 */
class AlarmReceiver : BroadcastReceiver() {
    private var request: SyncStepRequest? = null
    private var syncedStep = 0
    override fun onReceive(context: Context, intent: Intent) {
        //        context.startService(new Intent(context, LongRunningService.class));
        LogUtils.i("bluetooth", "执行后台长任务--------")
        if (BleManager.getInstance().isConnected) {
            BleManager.getInstance().dataComonent.getActivityCount { snNumber ->
                BleManager.getInstance().dataComonent.getStep(snNumber, 0, object : BleStepCallback {
                    override fun getStep(step: Int) {
                        BleLog.i("总步数-------$step")
                        EventBus.getDefault().post(WatchStepEvent(step))
                        syncStep(step)


                    }

                    override fun getOneceStep(step: Int) {
                        BleLog.i("单步数-------$step")
                    }
                })
            }
        }
    }

    fun syncStep(step: Int) {
        RetorfitServiceManger
                .observe(RetorfitServiceManger.instance!!.apiService.syncStep(DataConverter.instance.toJson(SyncStepRequest(BleManager.getInstance().connecredDevice.mac, step))))
                .subscribe(object : FilterSubscriber2<NoDataResponseBean>(BraceletApplication.context) {
                    override fun success(bean: NoDataResponseBean) {
                        EventBus.getDefault().post(SyncStepCount(step))
                    }

                    override fun fail(msg: String?) {
                    }


                })
    }

}
